package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.UserDataIsolation;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.QueryVo;
import com.ruoyi.system.mapper.ProjectAuthorizeMapper;
import com.ruoyi.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProjectAuthorizeServiceImpl implements IProjectAuthorizeService {

    @Autowired
    private ProjectAuthorizeMapper projectAuthorizeMapper;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private IPointCheckService pointCheckService;
    @Autowired
    private IReportTimedService reportTimedService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDeptService sysDeptService;

    @Override
    public List<ProjectAuthorize> queryAllUserInfo(ProjectAuthorize projectAuthorize) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id",projectAuthorize.getProjectId());
        Project retrieve = projectService.retrieve(queryVo);
        projectAuthorize.setDeptId(retrieve.getDeptId());
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        boolean flag = sysDeptService.checkIsCustomer(sysUser.getDeptId());
        Set<ProjectAuthorize> projectAuthorizes = new HashSet<>();
        //不是客户公司查询全部人
        if (!flag){
            //查询当前公司非（客户和巡检工和安装工）角色用户
            projectAuthorizes = projectAuthorizeMapper.queryCompanyUser(projectAuthorize);
        }
        //查询当前客户公司下面的用户信息
        List<ProjectAuthorize> customerUsers = projectAuthorizeMapper.queryAllUserInfo(projectAuthorize);
        if (CollUtil.isNotEmpty(customerUsers)){
            projectAuthorizes.addAll(customerUsers);
        }
        //查询当前项目授权的用户信息
        List<ProjectAuthorize> authorizes = projectAuthorizeMapper.queryAuthorizeUserInfo(projectAuthorize);
        if (CollUtil.isNotEmpty(authorizes)){
            Set<Integer> collect = authorizes.stream().map(ProjectAuthorize::getUserId).collect(Collectors.toSet());
            projectAuthorizes = projectAuthorizes.stream().filter(a -> !collect.contains(a.getUserId())).collect(Collectors.toSet());
        }
        if (!CollectionUtils.isEmpty(projectAuthorizes)){
            projectAuthorizes.forEach(a ->{
                a.setProjectId(projectAuthorize.getProjectId());
            });
        }
        return new ArrayList<>(projectAuthorizes);
    }

    @Override
    public List<ProjectAuthorize> queryAuthorizeUserInfo(ProjectAuthorize projectAuthorize) {
        return projectAuthorizeMapper.queryAuthorizeUserInfo(projectAuthorize);
    }

    @Override
    public Boolean addBatch(List<ProjectAuthorize> projectAuthorizes) {
        if (!CollectionUtils.isEmpty(projectAuthorizes)){
            projectAuthorizes.forEach(a -> {
                a.setIsOwner(0);
                projectAuthorizeMapper.add(a);
            });
        }
        return true;
    }

    @Override
    public Boolean add(ProjectAuthorize projectAuthorize) {
        return projectAuthorizeMapper.add(projectAuthorize) > 0;
    }

    @Override
    @Transactional
    public Boolean delete(String ids, SysUser sysUser) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        boolean flag = sysDeptService.checkIsCustomer(sysUser.getDeptId());
        String[] split = ids.split(",");
        for (int i = 0; i < split.length; i++) {
            ProjectAuthorize authorize = new ProjectAuthorize();
            int parseInt = Integer.parseInt(split[i]);
            authorize.setId(parseInt);
            ProjectAuthorize projectAuthorize = projectAuthorizeMapper.getOne(authorize);
            if (projectAuthorize == null){
                continue;
            }
            Integer roleId = projectAuthorize.getRoleId();
            if (flag){
                //客户设备管理员，只能删除客户巡检工和客户安装工
                if (roleId.compareTo(104) != 0 && roleId.compareTo(103) != 0){
                    throw new CustomException("客户设备管理员角色只能解除客户巡检工和客户安装工角色的用户授权");
                }
            }else {
                //设计员，只能删除客户设备管理员和现场工程师
                if (roleId.compareTo(102) != 0 && roleId.compareTo(105) != 0){
                    throw new CustomException("设计员角色只能解除客户设备管理员和现场工程师角色的用户授权");
                }
            }
            if (projectAuthorize.getIsOwner() == 1){
                throw new CustomException("删除失败！" + projectAuthorize.getUserName() + "是该项目的创建人");
            }
            checkProjectIsAuthorizeWithProjectId(sysUser,projectAuthorize.getProjectId());
            projectAuthorizeMapper.delete(authorize);
        }
        return true;
    }

    @Override
    @UserDataIsolation
    public Set<Integer> getProjectIdsByUserId(ProjectAuthorize projectAuthorize) {
        List<ProjectAuthorize> projectAuthorizes = projectAuthorizeMapper.checkProjectIsOwnerByUserId(projectAuthorize);
        if (CollUtil.isEmpty(projectAuthorizes)){
            return new HashSet<>();
        }
        List<ProjectAuthorize> authorizes = projectAuthorizes.stream().filter(a -> a.getIsOwner() == 1).collect(Collectors.toList());
        if (CollUtil.isEmpty(authorizes)){
            return new HashSet<>();
        }
        return authorizes.stream().map(ProjectAuthorize::getProjectId).collect(Collectors.toSet());
    }

    @Override
    @UserDataIsolation
    public Boolean checkProjectIsOwner(ProjectAuthorize projectAuthorize) {
        List<ProjectAuthorize> projectAuthorizes = projectAuthorizeMapper.checkProjectIsOwnerByUserId(projectAuthorize);
        if (CollUtil.isEmpty(projectAuthorizes)){
            return false;
        }
        ProjectAuthorize authorize = projectAuthorizes.get(0);
        return authorize.getIsOwner() == 1;
    }

    @Override
    @UserDataIsolation
    public Boolean checkProjectIsAuthorize(ProjectAuthorize projectAuthorize) {
        List<ProjectAuthorize> projectAuthorizes = projectAuthorizeMapper.checkProjectIsOwnerByUserId(projectAuthorize);
        if (CollUtil.isEmpty(projectAuthorizes)){
            return false;
        }
        return true;
    }

    @Override
    public void checkProjectIsAuthorizeWithDeviceId(SysUser sysUser, Integer deviceId) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", deviceId);
        Device device = deviceService.retrieve(queryVo);
        if (device == null){
            throw new CustomException("操作失败！没有查询到产品信息。");
        }
        if (device.getProjectId() == null || device.getProjectId() == 0){
            return;
        }
        ProjectAuthorize authorize = new ProjectAuthorize();
        authorize.setUserId(Convert.toInt(sysUser.getUserId()));
        authorize.setProjectId(device.getProjectId());
        boolean commonRoleFlag = sysUserService.checkUserIsCommonRole(sysUser);
        //设计员角色用户
        if (commonRoleFlag){
            //判断该项目是否是客户公司创建
            QueryVo vo = new QueryVo();
            vo.filters.put("project_id",device.getProjectId());
            boolean flag = projectService.checkProjectCreateByIsCustomer(vo);
            if (flag){
                throw new CustomException("当前用户不能操作！请用客户账号进行操作！");
            }
        }
        if (!checkProjectIsAuthorize(authorize)){
            throw new CustomException("操作失败！当前用户不是该产品所属项目的授权者。");
        }
    }

    @Override
    public void checkProjectIsAuthorizeWithProjectId(SysUser sysUser, Integer projectId) {
        ProjectAuthorize authorize = new ProjectAuthorize();
        authorize.setUserId(Convert.toInt(sysUser.getUserId()));
        authorize.setProjectId(projectId);
        boolean commonRoleFlag = sysUserService.checkUserIsCommonRole(sysUser);
        //设计员角色用户
        if (commonRoleFlag){
            //判断该项目是否是客户公司创建
            QueryVo vo = new QueryVo();
            vo.filters.put("project_id",projectId);
            boolean flag = projectService.checkProjectCreateByIsCustomer(vo);
            if (flag){
                throw new CustomException("当前用户不能操作！请用客户账号进行操作！");
            }
        }
        if (!checkProjectIsAuthorize(authorize)){
            throw new CustomException("操作失败！当前用户不是该项目的授权者。");
        }
    }

    @Override
    public void checkDeviceOperationStatus(SysUser sysUser, Integer deviceId) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", deviceId);
        Device device = deviceService.retrieve(queryVo);
        if (device == null){
            throw new CustomException("操作失败！没有查询到产品信息");
        }
        String userName = sysUser.getUserName();
        if (!StrUtil.equals(device.getCreateBy(),userName)){
            throw new CustomException("操作失败！该产品(" + device.getName() + ")不是由当前用户创建");
        }
    }

    @Override
    public void checkPointCheckOperationStatus(SysUser sysUser, Integer pointId) {
        PointCheck param = new PointCheck();
        param.setId(pointId);
        PointCheck pointCheck = pointCheckService.getOne(param);
        if (pointCheck == null){
            throw new CustomException("操作失败！没有查询到计划信息");
        }
        String userName = sysUser.getUserName();
        if (!StrUtil.equals(pointCheck.getCreateBy(),userName)){
            throw new CustomException("操作失败！该计划(" + pointCheck.getName() + ")不是由当前用户创建");
        }
    }

    @Override
    public void checkPointCheckTaskOperationStatus(SysUser sysUser, Integer taskId) {
//        PointCheckTask param = new PointCheckTask();
//        param.setId(taskId);
//        PointCheckTask pointCheckTask = pointCheckTaskService.getOne(param);
//        if (pointCheckTask == null){
//            throw new CustomException("操作失败！没有查询到该任务信息");
//        }
//        checkPointCheckOperationStatus(sysUser,pointCheckTask.getPointId());
    }

    @Override
    public void checkReportOperationStatus(SysUser sysUser, Integer reportId) {
        ReportTimed param = new ReportTimed();
        param.setId(reportId);
        ReportTimed reportTimed = reportTimedService.getOne(param);
        if (reportTimed == null){
            throw new CustomException("操作失败！没有查询到定时报表信息");
        }
        String userName = sysUser.getUserName();
        if (!StrUtil.equals(reportTimed.getCreateBy(),userName)){
            throw new CustomException("操作失败！该定时报表(" + reportTimed.getName() + ")不是由当前用户创建");
        }
    }

}
